<template>
    <div class="transactions-page">
        <div class="container py-3">
            <!-- 👉 顶部操作栏 -->
            <!-- 顶部操作栏：添加账单 + 筛选按钮 -->
            <div
                class="card shadow-md p-3 mb-3 rounded-xl border-0 bg-white/95 backdrop-blur-sm transition-all duration-300 hover:shadow-lg">
                <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
                    <!-- 添加账单按钮 -->
                    <button
                        class="btn btn-sm btn-primary px-4 py-2 rounded-lg shadow-sm hover:shadow transition-all transform hover:-translate-y-0.5"
                        @click="openAddModal">
                        <i class="bi-plus-lg me-1"></i> 添加账单
                    </button>

                    <!-- 筛选按钮 -->
                    <button class="btn btn-sm btn-outline-secondary px-4 py-2 rounded-lg"
                        @click="isFilterCollapsed = !isFilterCollapsed">
                        <i :class="isFilterCollapsed ? 'bi-funnel' : 'bi-x-lg'" class="me-1"></i>
                        {{ isFilterCollapsed ? '筛选' : '关闭筛选' }}
                    </button>
                </div>

                <!-- 展开后显示筛选表单 -->
                <transition name="fade">
                    <div v-show="!isFilterCollapsed" class="mt-3">
                        <SearchFilter ref="searchFilterRef" @filter="applyFilter" />
                    </div>
                </transition>
            </div>

            <!-- 📊 总计统计区 -->
            <div v-if="!groupedDataLoading && summaryData" class="card shadow-sm p-3 mb-4 rounded-xl border-0">
                <div class="row text-center">
                    <div class="col-4 border-end border-opacity-25">
                        <div class="fs-7 text-opacity-75">总收入</div>
                        <div class="fs-5 fw-bold text-success">{{ formatCurrency(summaryData.totalRevenue) }}</div>
                    </div>
                    <div class="col-4 border-end border-opacity-25">
                        <div class="fs-7 text-opacity-75">总支出</div>
                        <div class="fs-5 fw-bold text-danger">{{ formatCurrency(summaryData.totalExpenditure) }}</div>
                    </div>
                    <div class="col-4">
                        <div class="fs-7 text-opacity-75">总余额</div>
                        <div class="fs-5 fw-bold">{{ formatCurrency(summaryData.totalBalance) }}</div>
                    </div>
                </div>
            </div>

            <!-- 📦 账单展示区 -->
            <div class="grouped-transactions py-1">
                <!-- loading 状态 -->
                <Skeleton v-if="groupedDataLoading" :rows="6" :lines="2" :show-avatar="true" />

                <!-- 空状态 -->
                <EmptyState v-else-if="groupedDataSafe.length === 0" icon="📦" title="空空如也" description="当前还没有任何账单记录">
                    <button class="btn btn-primary mt-3" @click="openAddModal">添加第一条账单</button>
                </EmptyState>

                <!-- 有数据，按日期分组展示 -->
                <ul v-else class="list-group">
                    <div v-for="group in groupedDataSafe" :key="group.date"
                        class="card mb-3 p-3 rounded-xl shadow-sm bg-white/95 backdrop-blur-sm border-0 border-gray-100 transition-all duration-300 hover:shadow-md hover:-translate-y-0.5">
                        <!-- 分组头部 -->
                        <div class="d-flex justify-content-between align-items-center mb-2 text-muted small flex-wrap">
                            <h6 class="fw-semibold mb-0 fs-6">{{ group.date }}</h6>
                            <div class="d-flex gap-2">
                                <span>支出：<span class="amount-negative fs-6">{{
                                    group.expenditure.toFixed(2)
                                        }}</span></span>
                                <span>收入：<span class="amount-positive fs-6">{{
                                    group.revenue.toFixed(2)
                                        }}</span></span>
                            </div>
                        </div>

                        <!-- 每一条账单记录 -->
                        <div v-for="(item, index) in group.infos" :key="item.id"
                            class="d-flex py-3 px-2 align-items-center rounded-lg transition-all duration-200 hover:bg-gray-50"
                            :class="{ 'border-bottom': index !== group.infos.length - 1 }">
                            <!-- 分类图标 -->
                            <i :class="[item.categoryInfo.icon, item.categoryInfo.color]" class="me-3 flex-shrink-0"
                                style="font-size: 1.2rem"></i>

                            <!-- 描述文本（可点击编辑） -->
                            <div class="flex-grow-1 text-break">
                                <a href="#" class="text-decoration-none text-secondary fw-semibold"
                                    @click.prevent="onEditTransaction(item)">
                                    {{ item.desc }}
                                </a>
                            </div>

                            <!-- 金额 + 删除按钮 -->
                            <div class="d-flex align-items-center ms-3 gap-3 flex-shrink-0 text-nowrap">
                                <span :class="item.type === 0 ? 'text-secondary' : 'text-secondary'">
                                    {{ item.type === 0 ? '+' : '-' }}{{ item.amount.toFixed(2) }}
                                </span>
                                <i class="bi-trash3-fill text-danger pointer" @click.prevent="onDeleteTransaction(item)"
                                    title="删除"></i>
                            </div>
                        </div>
                    </div>
                </ul>
            </div>
        </div>

        <!-- ✅ 添加 / 编辑模态框 -->
        <Modal v-model:show="showFormModal" :title="editingTransaction ? '编辑账单' : '添加账单'">
            <TransactionForm :key="editingTransaction?.id || 'new'" :initial-data="editingTransaction"
                @saved="onTransactionSaved" @cancel="showFormModal = false" />
        </Modal>

        <!-- ✅ 删除确认弹窗 -->
        <Modal v-model:show="showDeleteModal" title="确认删除">
            <div class="d-flex align-items-center gap-3">
                <i class="bi bi-exclamation-triangle-fill text-danger fs-2"></i>
                <p class="mb-0 fw-semibold">确定删除这条账单吗？删除后不可恢复！</p>
            </div>
            <template #footer>
                <button class="btn btn-secondary me-2" @click="showDeleteModal = false" :disabled="deleting">
                    取消
                </button>
                <button class="btn btn-danger" @click="confirmDelete" :disabled="deleting">
                    <span v-if="deleting" class="spinner-border spinner-border-sm me-2"></span>
                    删除
                </button>
            </template>
        </Modal>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '../store/auth';

import SearchFilter from '../components/SearchFilter.vue';
import TransactionForm from '../components/TransactionForm.vue';
import Modal from '../components/Modal.vue';
import EmptyState from '../components/ui/EmptyState.vue';
import Skeleton from '../components/ui/Skeleton.vue';

import { useToast } from '../composables/useToast';
import { useApi } from '../composables/useApi';

const { success, error, warning } = useToast();
const auth = useAuthStore();
const router = useRouter();

// ✅ 筛选参数响应式
const filterParams = ref({});
const isFilterCollapsed = ref(true);

// ✅ 请求账单数据（使用 useApi 组合函数）
const {
    result: groupedData,
    fetchData: fetchGroupedData,
    loading: groupedDataLoading
} = useApi({
    url: '/transactions/search',
    method: 'GET',
    manual: true,
    transform: res => ({
        data: res.data, // 提取交易数据数组
        // 获取总计数据
        totalBalance: res.totalBalance,
        totalExpenditure: res.totalExpenditure,
        totalRevenue: res.totalRevenue
    }),
    params: () => filterParams.value
});

// null 安全处理
const groupedDataSafe = computed(() => (Array.isArray(groupedData.value?.data) ? groupedData.value.data : []));

// 📊 总计数据
const summaryData = computed(() => {
    // 检查 groupedData.value 是否包含总计信息
    if (groupedData.value && typeof groupedData.value === 'object' && !Array.isArray(groupedData.value)) {
        return {
            totalBalance: groupedData.value.totalBalance || 0,
            totalExpenditure: groupedData.value.totalExpenditure || 0,
            totalRevenue: groupedData.value.totalRevenue || 0
        };
    }
    return null;
});

// 📊 格式化货币显示
function formatCurrency(value) {
    const isNegative = value < 0;
    const absoluteValue = Math.abs(value);
    return `${isNegative ? '-' : ''}${parseFloat(absoluteValue.toFixed(2)).toLocaleString()}`;
}

// ✅ 控制状态
const editingTransaction = ref(null);
const showFormModal = ref(false);
const deletingItem = ref(null);
const deleting = ref(false);
const showDeleteModal = ref(false);

// ✅ 新增账单
function openAddModal() {
    editingTransaction.value = null;
    showFormModal.value = true;
}

// ✅ 编辑账单
function onEditTransaction(item) {
    editingTransaction.value = { ...item };
    showFormModal.value = true;
}

// ✅ 保存完成，刷新数据
function onTransactionSaved() {
    showFormModal.value = false;
    fetchGroupedData();
}

// ✅ 删除逻辑
function onDeleteTransaction(item) {
    deletingItem.value = item;
    showDeleteModal.value = true;
}

// ✅ 删除事务
const { fetchData: deleteTransaction, result: deleteResult } = useApi({
    url: `/transactions/delete/${deletingItem.value?.id}`,
    method: 'DELETE',
    toast: true,
    manual: true
});

async function confirmDelete() {
    if (!deletingItem.value || deleting.value) return;
    deleting.value = true;

    try {
        await deleteTransaction();
        const delRes = deleteResult.value;
        if (delRes.code !== 0) {
            error(delRes.msg || '删除失败');
            return;
        }
        success('删除成功！');
        showDeleteModal.value = false;
        deletingItem.value = null;
        fetchGroupedData();
    } catch (e) {
        error(`删除失败：${e}`);
    } finally {
        deleting.value = false;
    }
}

const searchFilterRef = ref(null);

// ✅ 接收筛选组件发出的参数，更新请求
function applyFilter(newFilter) {
    filterParams.value = newFilter;
    fetchGroupedData({ params: newFilter }); // ✅ 把参数明确传进去
}

// ✅ 初始加载
onMounted(() => {
    // 在组件挂载后，调用SearchFilter的applyFilter方法来触发初始筛选
    nextTick(() => {
        if (searchFilterRef.value) {
            searchFilterRef.value.applyFilter();
        }
    });
});
</script>

<style scoped>
/* 金额数字样式优化 */
.amount-positive {
    color: #10b981 !important;
    font-weight: 600;
}

.amount-negative {
    color: #ef4444 !important;
    font-weight: 600;
}

/* 修复卡片阴影 */
.transactions-page .card {
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.07) !important;
}

.transactions-page .card:hover {
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3) !important;
}

/* 总计统计区样式 */
.bg-gradient-primary {
    background: linear-gradient(135deg, #007bff, #0056b3);
}

.fs-7 {
    font-size: 0.8rem;
}
</style>